package com.zrrd.jt_admin.manager.controller;


import com.zrrd.jt_admin.common.dto.LoginDto;
import com.zrrd.jt_admin.common.entity.Manager;
import com.zrrd.jt_admin.common.response.ResponseResult;
import com.zrrd.jt_admin.common.utils.ContextHolder;
import com.zrrd.jt_admin.common.utils.JwtUtils;
import com.zrrd.jt_admin.common.vo.ManagerPageVo;
import com.zrrd.jt_admin.common.vo.ManagerLoginVo;
import com.zrrd.jt_admin.common.vo.ManagerVo;
import com.zrrd.jt_admin.manager.service.ManagerService;
import io.jsonwebtoken.Claims;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author ZhangYK
 * @version 8.0
 * @title ManagerController
 * @description
 * @create 2024/6/25 20:17
 */
@Api(tags = "管理员管理-接口文档") //指定文档中Controller的名字
@RestController
@RequestMapping("/admin")
@Slf4j
public class ManagerController {
    private final String TOKEN = "TOKEN_";

    @Resource
    private ManagerService managerService;

    @Resource
    private RedisTemplate redisTemplate;

    //@ApiOperation(value = "这个是接口名",notes = "这个是当前接口功能描述")
    @ApiOperation(value = "管理员登录",notes = "当前接口是用来进行管理员登录")
    //响应信息
    @ApiResponses({
            @ApiResponse(code = 2040, message = "查询成功"),
            @ApiResponse(code = 2041, message = "查询失败"),
            @ApiResponse(code = 500, message = "服务器内部错误，请联系管理人员！"),
            @ApiResponse(code = 404, message = "请求路径没有或页面跳转路径不对")
    })
    @PostMapping("/login")
    @ResponseBody
    public ResponseResult login(@RequestBody LoginDto loginDto){
        if (StringUtils.isBlank(loginDto.getUsername()) || StringUtils.isBlank(loginDto.getPassword())){
            return ResponseResult.defaultResponse(null,"","登录参数不合法");
        }
        ManagerLoginVo managerLoginVo = managerService.login(loginDto.getUsername(), loginDto.getPassword());

        System.out.println(managerLoginVo.getToken());

        return ResponseResult.defaultResponse(managerLoginVo,"登录成功","登录失败，用户名或密码错误");
    }

    @ApiOperation(value = "管理员退出登录")
    @GetMapping("/logout")
    @ResponseBody
    public ResponseResult logout(HttpServletRequest request, HttpServletResponse response){
        response.setContentType("application/json;charset=utf-8");
        String token = request.getHeader("token");
        if (StringUtils.isBlank(token)){
            return ResponseResult.queryResponse(null);
        }
        Claims claimsBody = JwtUtils.getClaimsBody(token);
        Integer id = claimsBody.get("id", Integer.class);
        if (id == null){
            return ResponseResult.queryResponse(null);
        }
        Manager manager = managerService.getById(id);
        Boolean flag = redisTemplate.delete(TOKEN + id);
        if (!flag){
            return ResponseResult.queryResponse(null);
        }
        return ResponseResult.queryResponse(manager);
    }

    @ApiOperation(value = "分页查询接口",notes = "当前接口是用来分页查询的")
    //响应信息
    @ApiResponses({
            @ApiResponse(code = 2040, message = "查询成功"),
            @ApiResponse(code = 2041, message = "查询失败"),
            @ApiResponse(code = 500, message = "服务器内部错误，请联系管理人员！"),
            @ApiResponse(code = 404, message = "请求路径没有或页面跳转路径不对")
    })
    @GetMapping("/manager/{page}")
    @ResponseBody
    public ResponseResult findByPage(@PathVariable("page") Integer page,
                                     @RequestParam(value = "limit",required = false) Integer limit,
                                     @RequestParam(value = "keyword",required = false) String keyword){
//        System.out.println("当前页--》"+page);
//        System.out.println("每页多少条--》"+limit);
//        System.out.println("关键字--》"+keyword);
        if (limit == null){
            limit = 5;
        }

        ManagerPageVo managerPageVo=managerService.findByPage(page,limit,keyword);

        return ResponseResult.queryResponse(managerPageVo);
    }


    @ApiOperation(value = "查询单个管理员",notes = "根据id查询单个管理员")
    //响应信息
    @ApiResponses({
            @ApiResponse(code = 2040, message = "查询成功"),
            @ApiResponse(code = 2041, message = "查询失败"),
            @ApiResponse(code = 500, message = "服务器内部错误，请联系管理人员！"),
            @ApiResponse(code = 404, message = "请求路径没有或页面跳转路径不对")
    })
    //**URL**:`/admin/manager/:id`
    //http://localhost:80891/admin/manager/1
    @GetMapping("/manager/one/{id}")
    @ResponseBody
    public ResponseResult findById(@PathVariable("id")Integer id){
        Long aId = ContextHolder.getId();
        log.info("id为："+aId+"的管理员访问了findOne方法.....");
        if (StringUtils.isBlank(id.toString())||managerService.getById(id) == null){
            return ResponseResult.queryResponse(null);
        }
        Manager manager = managerService.getById(id);
        ManagerVo managerVo = new ManagerVo();
        BeanUtils.copyProperties(manager, managerVo);
        return ResponseResult.queryResponse(managerVo);
    }

    @ApiOperation(value = "增加管理员",notes = "增加管理员")
    ///admin/manager
    //http://localhost:80891/admin/manager/
    @PostMapping("/manager/")
    @ResponseBody
    public ResponseResult addManager(@RequestBody Manager manager){
//        System.out.println("username--"+username);
//        System.out.println("password--"+password);
//        System.out.println("avatar--"+avatar);
//        System.out.println("role_id--"+roleId);
//        System.out.println("status--"+status);
        if(manager==null){
            return ResponseResult.queryResponse(false);
        }
       return ResponseResult.addResponse(managerService.save(manager));
    }

    @ApiOperation(value = "修改", notes = "修改管理员用户信息")
    @PutMapping("/manager/")
    @ResponseBody
    public ResponseResult update(@RequestBody Manager manager){
        if(manager==null){
            return ResponseResult.queryResponse(false);
        }
        boolean flag = managerService.updateById(manager);
        return ResponseResult.updateResponse(flag);
    }

    @ApiOperation(value = "删除", notes = "根据id删除")
    @DeleteMapping("/manager/{id}/delete")
    @ResponseBody
    public ResponseResult remove(@PathVariable("id") Integer id) {
        boolean flag = managerService.removeById(id);
        return ResponseResult.removeResponse(flag);
    }

    @ApiOperation(value = "修改状态", notes = "根据id修改状态")
    @PutMapping("/manager/{id}/update_status")
    @ResponseBody
    public ResponseResult setStatus(@PathVariable("id") Integer id,Integer status) {
        Boolean bStatus=status==1?true:false;

        boolean flag = managerService.lambdaUpdate()
                .eq(Manager::getId, id)
                .set(Manager::getStatus, bStatus)
                .update();

        /*
            UpdateWrapper<Manager> uw=new UpdateWrapper<>();
            uw.eq("id",id);
            uw.set("status",status);
            boolean flag = managerService.update(uw);
        */

        return ResponseResult.updateResponse(flag);
    }

}
